<template>
  <div>
    <header>
      <a href="/show" class="headerback"><img src="/img/back.png"/></a>
      <div class="indexsearch">
        我的购物车
      </div>

      <a href="/home" class="index">
        <img src="/img/goindex.png" />
      </a>
    </header>

    <!-- 购物车 -->
    <!-- 提示登录 -->
    <div class="islogin" v-show="!this.IsLogin">
      现在登录同步电脑和手机购物车中商品
      <a href="/login">登录</a>
    </div>
    <!-- 购物车有商品 -->
    <div class="emptyCartDiv" v-show="this.cartList.lenght"></div>
    <div class="emptyDiv2" v-show="this.IsLogin"></div>
    <div
      class="cartWrap"
      v-show="cartList"
      v-for="(item, index) in cartList"
      :key="index"
    >
      <div class="cartCen">
        <div class="ck">
          <input
            name="checkbox"
            value="Item 1"
            type="checkbox"
            class="tui-checkbox "
            v-model="item.isCheck"
          />
        </div>
        <van-card
          class="vanCard"
          :price="item.price + '.0'"
          :desc="'尺码:' + item.size"
          :title="item.title"
          :thumb="item.src"
          @click="goodinfo(index)"
        />

        <div class="stepperWrap">
          <van-stepper
            class="stepper"
            style="display: inline;"
            v-model="item.num"
            @change="changeNum"
          />
        </div>
      </div>
    </div>
    <div class="emptyDiv" v-show="this.cartList.length"></div>

    <!-- 提交订单 -->
    <van-submit-bar
      class="submit-bar"
      :price="allPrice"
      button-text="去结算"
      @submit="onSubmit"
      v-show="this.cartList.length"
    >
      <input type="checkbox" class="tui-checkbox" v-model="allCheck" />全选
      <van-button type="danger" size="mini" class="clearCart" @click="delCar"
        >删除</van-button
      >
    </van-submit-bar>
  </div>
</template>

<script>
import appHeaders from "../components/headers";
import { Toast } from "vant";
import getuser from "../api/userApi";
import { getUser } from "../utils/auth";
export default {
  data() {
    return {
      result: [],
      cartList: [],
      submitTemp: [],
      submitItem: {},
      submitList: [],
      cartTemp: [],
      checked: "",
      allPrice: 0,
      buyNum: 1,
      IsLogin: false
    };
  },

  components: {
    appHeaders
  },

  methods: {
    onSubmit() {
      if (!this.IsLogin) {
        this.$router.push("/login");
      } else {
        this.submitTemp = this.cartList.filter(item => item.isCheck == true);
        if (this.submitTemp.length) {
          this.submitList = [];
          this.submitTemp.forEach(item => {
            let submitItem = {};
            submitItem.src = item.src;
            submitItem.title = item.title;
            submitItem.size = item.size;
            submitItem.price = item.price;
            submitItem.num = item.num;
            this.submitList.push(submitItem);
          });
          localStorage.setItem("order", JSON.stringify(this.submitList));
          localStorage.setItem("price", JSON.stringify(this.allPrice / 100));
          this.$router.push("/order");
        } else {
          Toast("请先选择需要结算商品");
        }
      }
    },
    onClickEditAddress() {},

    // 判断是否登录
    isLogin() {
      let result = getUser();
      if (!result) {
        result = false;
      }
      this.IsLogin = result;
    },
    goodinfo(index) {
      // console.log(this.cartList[index].goodinfo);
      localStorage.setItem(
        "sku",
        JSON.stringify(this.cartList[index].goodinfo)
      );
      this.$router.push("/details");
    },
    // 判断购物车数量，是否渲染submit面板
    changeNum() {
      // 发请求，存购物车
      getuser
        .getuser({ username: getUser() })
        .then(res => {
          if (res.data.code) {
            // console.log(res.data.data[0]._id);
            // 拿到用户_id,发送请求 修改用户信息
            getuser
              .editCart(res.data.data[0]._id, this.cartList)
              .then(res => {
                // 轻提示
              })
              .catch(err => {
                console.log("出错了" + err);
              });
          }
        })
        .catch(err => {
          console.log("出错了" + err);
        });

      localStorage.setItem("cart", JSON.stringify(this.cartList));
    },
    delCar() {
      this.cartList = this.cartList.filter(item => item.isCheck == false);
      if (!this.cartList.length) {
        this.$router.push("/cart2");
      }

      // 发请求，存购物车
      getuser
        .getuser({ username: getUser() })
        .then(res => {
          if (res.data.code) {
            // console.log(res.data.data[0]._id);
            // 拿到用户_id,发送请求 修改用户信息
            getuser
              .editCart(res.data.data[0]._id, this.cartList)
              .then(res => {
                // 轻提示
              })
              .catch(err => {
                console.log("出错了" + err);
              });
          }
        })
        .catch(err => {
          console.log("出错了" + err);
        });

      localStorage.setItem("cart", JSON.stringify(this.cartList));
    }
  },
  watch: {
    cartList: {
      deep: true,
      handler(newdata) {
        this.allPrice = 0;
        this.cartList.forEach(item => {
          if (item.isCheck) {
            this.allPrice += item.price * 100 * item.num;
          }
        });
      }
    }
  },
  computed: {
    allCheck: {
      get() {
        if (this.cartList) {
          return this.cartList.every(item => item.isCheck == true);
        }
      },
      set(val) {
        if (this.cartList) {
          this.cartList.forEach(item => {
            item.isCheck = val;
          });
        }
      }
    }
  },
  created() {
    // 刷新根据是否登录，渲染登录图标；
    this.isLogin();
    // console.log(this.IsLogin);
    if (this.IsLogin) {
      getuser
        .getuser({ username: getUser() })
        .then(res => {
          // console.log(res.data.data[0].addList);
          if (!res.data.data[0].cartList) {
            res.data.data[0].cartList = [];
          }

          let arr1 = res.data.data[0].cartList;
          let arr2 = JSON.parse(localStorage.getItem("cart"));

          for (let i = 0; i < arr1.length; i++) {
            for (let j = 0; j < arr2.length; j++) {
              if (arr1[i].sku == arr2[j].sku && arr1[i].size == arr2[j].size) {
                arr1[i] = arr2[j];
                // arr1[i].num = arr1[i].num + arr2[j].num;
              }
            }
          }

          for (let i = 0; i < arr2.length; i++) {
            let temp = arr1.some(
              j => arr2[i].sku == j.sku && arr2[i].size == j.size
            );
            if (!temp) {
              arr1.unshift(arr2[i]);
            }
          }
          this.cartList = arr1;
          localStorage.setItem("cart", JSON.stringify(this.cartList));

          if (!this.cartList.length) {
            this.$router.push("/cart2");
          }
        })
        .catch(err => {
          console.log(err);
        });
    } else {
      // 刷新购物车数据，渲染submit面板；
      if (
        !JSON.parse(localStorage.getItem("cart")) ||
        !JSON.parse(localStorage.getItem("cart")).length
      ) {
        this.cartList = [];
        this.$router.push("/cart2");
      } else {
        this.cartList = JSON.parse(localStorage.getItem("cart"));
      }
    }
  }
};
</script>

<style scoped lang="scss">
@import "@/assets/sass/common.scss";
@import "@/assets/sass/vw.scss";
header {
  display: flex;
  justify-content: space-between;
  background-color: #f5f5f5;
  position: fixed;
  top: 0;
  z-index: 1;

  .headerback img {
    width: v(40);
    height: v(50);
  }

  .indexsearch {
    width: v(286);
    height: v(50);
    // background-color: orange;
    text-align: center;
    line-height: v(50);
  }
  .index img {
    width: v(46);
    height: v(50);
  }
}

//购物车
.islogin {
  background: #fff;
  width: 100%;
  height: 2.8rem;
  line-height: 2.8rem;
  text-align: center;
  // background-color: orange;
  margin-top: v(50);
}
.islogin a {
  display: inline-block;
  width: 2.5rem;
  height: 2.2rem;
  color: #d70057;
  line-height: 2.2rem;
  text-align: center;
}
.emptyCartDiv {
  height: v(45);
}
.emptyDiv2 {
  height: v(40);
}
.cartWrap {
  height: v(116);
  margin-top: v(18);
  background-color: white;
  .ck {
    width: v(38);
    height: v(116);
    float: left;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .cartCen {
    width: 100vw-v(38)-v(20);
    height: v(116);
    padding: v(6) v(10) v(6) 0;
    position: relative;
  }
  .vanCard {
    width: 87vw;
    height: v(104);
    float: right;
    display: block;
    font-size: v(14);
    display: flex;

    .van-card__thumb {
      width: v(104);
      height: v(104);
    }
    .van-card__desc {
      margin-top: v(12);
      color: #999;
    }
    .van-card__price {
      font-size: v(16);
      color: #d70057;
    }
    .van-card__num {
      color: white;
    }
  }
  .stepperWrap {
    position: absolute;
    width: v(120);
    height: v(60);
    bottom: v(10);
    right: v(10);
    .stepper {
      position: absolute;
      bottom: v(5);
      right: 0;
    }
  }
}
.tui-checkbox:checked {
  background: #d70057;
}
.tui-checkbox {
  width: 25px;
  height: 25px;
  background-color: #ffffff;
  border: solid 1px #dddddd;
  -webkit-border-radius: 50%;
  border-radius: 50%;
  font-size: 0.8rem;
  margin: 0;
  padding: 0;
  position: relative;
  display: inline-block;
  vertical-align: top;
  cursor: default;
  -webkit-appearance: none;
  -webkit-user-select: none;
  user-select: none;
  -webkit-transition: background-color ease 0.1s;
  transition: background-color ease 0.1s;
}
.tui-checkbox:checked::after {
  content: "";
  top: 5px;
  left: 5px;
  position: absolute;
  background: transparent;
  border: #fff solid 2px;
  border-top: none;
  border-right: none;
  height: 6px;
  width: 10px;
  -moz-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
  transform: rotate(-45deg);
}

.emptycart {
  background-color: #eeeeee;
  padding-bottom: v(16);
  .emptycartdiv {
    height: v(50);
  }
}
.emptycart p {
  text-align: center;
  line-height: 1rem;
  color: #999;
  font-size: 1rem;
  display: flex;
  justify-content: center;
  img {
    width: v(120);
    height: v(120);
  }
}
.emptycart table {
  width: 80%;
  margin: 1.3rem auto 1.5rem;
}
.emptycart table td {
  width: 50%;
}
.emptycart table a {
  display: block;
  color: #d70057;
  text-align: center;
  border: 1px solid #d70057;
  line-height: 1.75rem;
  height: 1.85rem;
  width: 7.5rem;
  margin: 0 auto;
  border-radius: 0.15rem;
}
.emptycart img {
  width: 6rem;
  margin: 2rem 0 1rem;
}
.emptycart .link {
  width: 50%;
}

.cartList {
  font-size: v(14);
  // padding: 0 v(2);
}

.emptyDiv {
  width: 100%;
  height: v(110);
}

.submit-bar {
  width: 100%;
  height: v(50);
  padding-left: v(8);
  position: fixed;
  left: 0;
  bottom: v(51);
  .van-checkbox {
    padding-left: v(10);
  }
  .van-submit-bar__text {
    padding-right: v(10);
  }
}
.clearCart {
  margin-left: v(8);
}
</style>
